<template>
  <el-card>
    <div slot="header">
      <h3>维护资质信息</h3>
    </div>
    <el-row type="flex" justify="end">
      <el-button
        size="large"
        type="text"
        :loading="btnLoading.submit"
        @click="handleSubmitData"
        >保存</el-button
      >
    </el-row>
    <el-row>
      <SkusTable
        showActionCol
        :showSelectCol="false"
        :showPagination="false"
        :defaultMinWidth="120"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :actionRender="renderActionBtnFn"
      />
    </el-row>
    <!-- 设置资质弹框 -->
    <SetQualificationDialog
      :visible.sync="setQualification.visible"
      :dimensionKey="setQualification.dimensionKey"
      :handleAssociate="qualificationLinkedFn"
      :handleCancel="qualificationCanceledFn"
      :handleQuery="qualificationSearchedFn"
      actionBtnName="设置资质"
      @refreshIndexPage="reloadTableDataFn"
    />
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import SkusTable from '@/components/skusTable';
import SetQualificationDialog from '@/pages/commodity/components/SetQualificationDialog';
import { tableColumns } from '@/pages/commodity/addSkuToSpu/constants/skuToBePerfect/skuQualificationInfo';
import { isResponseSuccess, isResponseSuccessState } from '@/utils/bizUtils';
export default {
  components: {
    SkusTable,
    SetQualificationDialog
  },
  data () {
    return {
      productUuid: '',
      tableInfo: {
        columns: tableColumns,
        list: [],
        loading: false
      },
      setQualification: {
        visible: false,
        dimensionKey: 'uuid',
      },
      currentRowData: {
        relUuid: '',
        relUuidKey: 'uuid', // 点击设置资质时，进入弹框的表格的uuid的所取字段名
      },
      btnLoading: {
        submit: false
      },
      apiObj: {
        getQualificationByProductUuid: { // 查询资质信息接口
          url: '/sysback/product/addSku/qualificationInfo/getQualificationByProductUuid',
          type: 'post'
        },
        saveQualificationInfo: { // 保存资质信息接口
          url: '/sysback/product/addSku/qualificationInfo/saveQualificationInfo',
          type: 'post'
        },
        getAuditRelByCondition: { // 关联资质弹框-查询接口（已关联）
          url: '/sysback/qualification/getAuditRelByCondition',
          type: 'post'
        },
        getAuditNotRelByCondition: { // 关联资质弹框-查询接口（未关联）
          url: '/sysback/qualification/getAuditNotRelByCondition',
          type: 'post'
        },
        createAuditRelate: { // 关联资质弹框-关联接口
          url: '/sysback/qualificationskuqualificationrel/createAuditRelate',
          type: 'post'
        },
        deleteQualificationAuditRelate: { // 关联资质弹框-取消关联接口
          url: '/sysback/product/addSku/qualificationInfo/deleteQualificationAuditRelate',
          type: 'post'
        }
      }
    }
  },
  mounted () {
    const { productUuid } = this.$route.query;
    this.productUuid = productUuid;
    this.getTableDataFn();
  },
  methods: {
    // 操作栏按钮渲染
    renderActionBtnFn (h, { row }) {
      return (<div class="table-action">
        {<el-button
          size="mini"
          type="text"
          onClick={() => this.handleSetQualification(row)}
        >设置资质</el-button>}
      </div>);
    },
    // 获取表格数据
    async getTableDataFn () {
      const data = {};
      const { url, type } = this.apiObj.getQualificationByProductUuid;
      const apiUrl = `${url}?productUuid=${this.productUuid}`;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(apiUrl, type, data, false);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          this.tableInfo.list = res.retData.quaList;
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 重新加载表格数据
    reloadTableDataFn () {
      this.getTableDataFn();
    },
    // 提交
    async handleSubmitData () {
      const data = {};
      const { url, type } = this.apiObj.saveQualificationInfo;
      const apiUrl = `${url}?productUuid=${this.productUuid}`;
      try {
        this.btnLoading.submit = true;
        const res = await ApiRequest(apiUrl, type, data, false);
        this.btnLoading.submit = false;
        if (isResponseSuccessState(res.retStatus)) {
          this.$message.success('保存成功');
          this.$router.go(-1)
        }
      } catch (err) {
        this.btnLoading.submit = false;
      }
    },
    // 设置资质
    handleSetQualification (row) {
      const curBtnId = getBtnsId('设置资质');
      sessionStorage.setItem('buttonId', curBtnId);
      const { relUuidKey } = this.currentRowData;
      this.currentRowData.relUuid = row[relUuidKey];
      this.setQualification.visible = true;
    },
    // 关联资质
    async qualificationLinkedFn (row) {
      const data = {
        relUuid: this.currentRowData.relUuid,
        qualificationUuids: row[this.setQualification.dimensionKey]
      }
      const { url, type } = this.apiObj.createAuditRelate;
      const res = await ApiRequest(url, type, data, true);
      if (isResponseSuccessState(res.retStatus)) {
        return true;
      }
      return false;
    },
    // 取消关联资质
    async qualificationCanceledFn (row) {
      const data = {
        relUuid: this.currentRowData.relUuid,
        qualificationUuids: row[this.setQualification.dimensionKey]
      };
      const { url, type } = this.apiObj.deleteQualificationAuditRelate;
      const res = await ApiRequest(url, type, data, true);
      if (isResponseSuccessState(res.retStatus)) {
        return true;
      }
      return false;
    },
    // 关联资质信息查询
    async qualificationSearchedFn ({ params, formData, tabsStatus }) {
      const { url, data } = this.getQualicationSearchedParamsFn({ params, formData, tabsStatus });
      const res = await ApiRequest(url, 'post', data);
      if (isResponseSuccess(res)) { return res.retData; }
      return false;
    },
    // 获取关联资质查询接口入参
    getQualicationSearchedParamsFn ({ params, formData, tabsStatus }) {
      const { relUuid, qualificationCate } = this.currentRowData;
      const url = {
        firstTab: `${this.apiObj.getAuditNotRelByCondition.url}?relUuid=${relUuid}`,
        secondTab: `${this.apiObj.getAuditRelByCondition.url}?relUuid=${relUuid}`
      };
      let searchData = []
      for (var key in formData) {
        searchData.push({
          name: key,
          value: formData[key]
        },
        {
          name: `${key}_q`,
          value: 'Like'
        });
      }
      const { pagination, sort } = params;
      const searchParam = [
        ...searchData,
        { name: 'qualificationCate', value: qualificationCate },
        { name: 'qualificationCate_q', value: 'EQ' },
      ];
      const data = {
        ...pagination,
        ...sort,
        searchParam: JSON.stringify(searchParam)
      };
      return {
        url: url[tabsStatus] || '',
        data
      };
    },
  }
}
</script>
